//                component = new MapView(containerId, componentId, options);
// map Start
function MapView(containerId, componentId, options) {

    this.COMPONENT_TYPE = "map-view";
    
    this.CONFIG_TYPE_DATA_SOURCE = TYPE_DATA_SOURCE;
    this.CONFIG_TYPE_CONSTANT = TYPE_CONSTANT;
    
    var defaultOptions = {
        width : 512,
        height : 512,
        label : {
            type : this.CONFIG_TYPE_CONSTANT,
            object : {
                name: "",
            }
        },
        params : [],
    };

    var opts = $.extend({}, defaultOptions, options);

    this.containerId = containerId;
    this.componentId = componentId;

    this.width = opts.width;
    this.height = opts.height;
    
    this.title = opts.title;
    this.params = opts.params;

}

MapView.prototype.init = function() {
    $("#"+this.containerId).append("<div style=\"width:100%; height:100%;  border: 1px solid #414042; padding: 5px; padding-top: 15px;\" id=\"" + this.componentId+"\"></div>");
    this.initMapView();
};

MapView.prototype.getConfig = function() {
    return this.params;
};

MapView.prototype.initMapView = function() {
    var lat = 10.7253272;
    var lon = 106.6175712;
    this.mapViewer = new OpenStreetMap();
    this.mapViewer.initMap(this.componentId.toString(),lon,lat);
//    this.mapViewer.clearContainer();
    this.mapViewer.setMapCenter(lon,lat);
    this.setAllMarker();
};

MapView.prototype.setAllMarker = function() {
    var lat = 10.7253272;
    var lon = 106.6175712;
    var mapEventClickMarkerhandle = function(evt){
        console.log('click marker Icon');
        if(boiler.deviceId != undefined && boiler.siteId != undefined){
           
        }
        OpenLayers.Event.stop(evt);
    };
    var markerIcon = IconUtil.getMapMarkerIcon();
    var paramMarkerPopup = {};
    paramMarkerPopup['deviceHost'] = "123123ASDA";
    paramMarkerPopup['deviceId'] = "ASDASD2354";
//    paramMarkerPopup['siteId'] = boiler.siteId;
    paramMarkerPopup['lon'] = lon;
    paramMarkerPopup['lat'] = lat;
//    paramMarkerPopup['popupContentHTML'] = popupContentHTML;
    paramMarkerPopup['imgUrl'] = markerIcon;
    paramMarkerPopup['mapEventClickMarkerhandle'] = mapEventClickMarkerhandle;
    paramMarkerPopup['closeBox'] = false;
    paramMarkerPopup['overflow'] = false;
    this.mapViewer.setMarkerPopup(paramMarkerPopup);
    
};
MapView.prototype.isWidgetMapView = function() {
    return true;
};

MapView.prototype.setConfigMapping = function(mapping) {
//    this.configMapping = mapping;
//    var params = this.getConfig();
//    if (params.length > 0) {
//        var paramCfg = mapping[params[0].pId];
//        this.unit = paramCfg['p-unit'];
//    }
//    var label = this.label;
//    var labelObj = label.object;
//    
//    var type = label.type;
//    var txtLabel = "Label 1:";
//    if(type == this.CONFIG_TYPE_CONSTANT) {
//        txtLabel = labelObj.name;
//    } else if(type == this.CONFIG_TYPE_DATA_SOURCE) {
//        var pId = labelObj.pId;
//        var name = labelObj.name;
//        txtLabel = mapping[pId][name];
//    }
//    this.txtLabel = txtLabel;
};

MapView.prototype.animateTo = function() {
    var currentVal = this.currentVal;
    var newVal = this.newVal;
    if (currentVal == newVal) {
        clearInterval(this.animation_loop);
        this.animation_loop = undefined;
    } else {
        // var decimalPart = Math.abs(parseInt(newVal) - newVal);
        if (currentVal < newVal) {
            currentVal++;
            if (currentVal > newVal) {
                currentVal = newVal;
            }
        } else {
            currentVal--;
            if (currentVal < newVal) {
                currentVal = newVal;
            }
        }
        this.currentVal = currentVal;
        this.init();
    }
};

MapView.prototype.prepareLiveView = function() {
    
};

MapView.prototype.getLiveViewCfg = function(json) {
//    var type = this.COMPONENT_TYPE;
//    var direction = this.direction;
//    var label = this.label;
//    var params = this.params;
//    json.type = type;
//    var config = {};
//    config.direction = direction;
//    config.label = label;
//    config.params = params;
//    json.config = config;
    return json;
};

function OpenStreetMap() {
    this.map = null;
    this.zoom = 18;
    this.markers = null;
    // var layer = null;
    this.arrPointMarker = [];
    this.currentPopup = null;
    this.popupClass = null;
    this.sizeIconMarker = null;
    // save current map view
    this.currentZoom = null;
    this.currentPointMapCenter = null;
    this.isSaveMapView = false;
    this.divContainer = null;
    
};

OpenStreetMap.prototype.initMap = function(container,lon,lat) {
    var fromProjection = new OpenLayers.Projection("EPSG:4326");   // Transform from WGS 1984
    var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
    var position = new OpenLayers.LonLat(lon, lat).transform( fromProjection, toProjection);
    this.popupClass = new OpenLayers.Class(OpenLayers.Popup.Anchored, {
          "autoSize": true,
          "minSize": new OpenLayers.Size(360, 150),
          "maxSize": new OpenLayers.Size(460, 200),
          "keepInMap": true
    });
    this.sizeIconMarker = new OpenLayers.Size(33,33);
    this.divContainer = container;
    this.map = new OpenLayers.Map({
        div: container,
        theme: null,
        projection: new OpenLayers.Projection("EPSG:900913"),
        displayProjection: new OpenLayers.Projection("EPSG:4326"),
        units: 'm',
        numZoomLevels: 18,
        maxResolution: 156543.0339,
        maxExtent: new OpenLayers.Bounds(
            -20037508.34, -20037508.34, 20037508.34, 20037508.34
        ),
        controls: [
            new OpenLayers.Control.Navigation(),
            new OpenLayers.Control.PanZoomBar()
        ],
        layers: [
            new OpenLayers.Layer.Google("Google ", { 
                sphericalMercator: true,
                projection:"EPSG:900913",
                transparent: true })
        ],
        center: position,
        zoom : this.zoom
    });
};

OpenStreetMap.prototype.clearContainer =  function(){
   if(this.divContainer != null){
       var divContainMap = $("div[id='"+this.divContainer+"']");
       divContainMap.html('');
   }
};

OpenStreetMap.prototype.setMapCenter =  function(lon,lat){
    var fromProjection = new OpenLayers.Projection("EPSG:4326");   // Transform from WGS 1984
    var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
    var position = new OpenLayers.LonLat(lon, lat).transform( fromProjection, toProjection);
    this.map.setCenter(position, 17);
};

OpenStreetMap.prototype.setMapCenterPoints = function() {
    var lngMin = parseFloat(this.getLngMin());
    var lngMax = parseFloat(this.getLngMax());
    var latMin = parseFloat(this.getLatMin());
    var latMax = parseFloat(this.getLatMax());
    var centerPoint = this.caculateCenterPoint(latMin,lngMin,
            latMax,lngMax,this.arrPointMarker.length);
    this.map.setCenter(centerPoint, this.zoom);
};

OpenStreetMap.prototype.changeIconMarker = function(param) {
    var marker = null;
    if(this.markers != null){
        for(var i = 0 ; i < this.markers.markers.length ; i++){
            if(this.markers.markers[i].deviceId == param.deviceId){
                //keep old marker
                marker = this.markers.markers[i];
                //remove marker from array markers from object map
                this.markers.removeMarker(this.markers.markers[i]);
            }
        }
    }
    if(marker != null){
        //create new icon object
        var offset = new OpenLayers.Pixel(-(this.sizeIconMarker.w), -(this.sizeIconMarker.h));
        var icon = new OpenLayers.Icon(param.imgUrl,this.sizeIconMarker,offset);
        //keep old feature object from marker do you want
        //change icon
        var feature = marker.feature;
        if(param.popupContentHTML !== undefined){
            feature.data.popupContentHTML = param.popupContentHTML;
            if(feature.popup != null){
                feature.popup.destroy();
                feature.popup = null;
            }
        }
        // set again new icon and feature object of marker do you want change
        var newMarker = new OpenLayers.Marker(marker.lonlat, icon.clone());
        
        newMarker.feature = feature;
        newMarker.deviceId = marker.deviceId;
        //newMarker = this.registerPopupMouseOutOver(feature,newMarker);
        
        //register again click handle of old marker 
        //to new merker
        newMarker = this.registerPopupMouseClick(feature, newMarker);
        
        this.markers.addMarker(newMarker);
    } 
};

OpenStreetMap.prototype.setMarkerPopup = function(paramMarkerPopup) {
    if(this.map !== null){
        if(this.markers === null){
            this.markers = new OpenLayers.Layer.Markers( "Markers" );
            this.map.addLayer(this.markers);
        }

        var positionMarker = [] || "";
        positionMarker.push(paramMarkerPopup.lon);
        positionMarker.push(paramMarkerPopup.lat);
        this.arrPointMarker.push(positionMarker);
        
        var lonLatMarker = new OpenLayers.LonLat(paramMarkerPopup.lon, paramMarkerPopup.lat)
            .transform(new OpenLayers.Projection("EPSG:4326"), 
            this.map.getProjectionObject());
        var feature = new OpenLayers.Feature(this.markers, lonLatMarker); 
        feature.closeBox = paramMarkerPopup.closeBox;
        feature.popupClass = this.popupClass;
        feature.data.popupContentHTML = paramMarkerPopup.popupContentHTML;
        feature.data.overflow = (paramMarkerPopup.overflow) ? "auto" : "hidden";
        
        
        var offset = new OpenLayers.Pixel(-(this.sizeIconMarker.w), -(this.sizeIconMarker.h));
        var icon = new OpenLayers.Icon(paramMarkerPopup.imgUrl,this.sizeIconMarker,offset);
        var lonLatIcon = new OpenLayers.LonLat(paramMarkerPopup.lon,paramMarkerPopup.lat).transform(
                new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
                this.map.getProjectionObject() // to Spherical Mercator Projection
        );
        var marker = new OpenLayers.Marker(lonLatIcon, icon.clone());
        marker.feature = feature;
            
       // marker = this.registerPopupMouseOutOver(feature, marker);
        marker = this.registerPopupMouseClick(feature, marker);
        //marker.events.register("click", feature,paramMarkerPopup.mapEventClickMarkerhandle);
        marker.deviceId = paramMarkerPopup.deviceId;
        marker.deviceHost = paramMarkerPopup.deviceHost;
//      marker.siteId = paramMarkerPopup.siteId;
        
        this.markers.addMarker(marker);
    }
};

OpenStreetMap.prototype.registerPopupMouseClick = function(feature,marker) {
    var seltParent = this;
    marker.events.register("click", feature,function(evt){
        var selt = this;
        if (this.popup === null) {
            this.popup = this.createPopup(this.closeBox);
            seltParent.map.addPopup(this.popup);
            this.popup.show();
        } else {
            this.popup.toggle();
        }
//        for(var i = 0 ; i < seltParent.markers.markers.length ; i++){
//            var marker = seltParent.markers.markers[i];
//            if(seltParent.marker.feature.id == selt.id){
//                var deviceId = marker.deviceId;
//                console.log(deviceId);
//                router.currentView.currentView.maps.initRealtimeData(deviceId);
//            }
//        }
       
        // start for handle click of icon close popup marker 
   
        if(selt.popup != null){
            var currentPopupId = selt.popup.id;
            // for case 1 :show popup is clicked to top viewer
//            $('#' + currentPopupId).click(function(){
//                $('#' + currentPopupId).css("z-index",999);
//                for(var i = 0 ; i < map.popups.length ; i++){
//                    if( currentPopupId != map.popups[i].id){
//                        $('#' + map.popups[i].id).css("z-index",998);
//                    }
//                }
//            });
            // for case 2 : show popup is clicked
            for(var i = 0 ; i < seltParent.map.popups.length ; i++){
                if( currentPopupId != seltParent.map.popups[i].id){
                    var popupId = seltParent.map.popups[i].id;
                    seltParent.map.removePopup(seltParent.map.popups[i]);
                    for(var i = 0 ; i < seltParent.markers.markers.length ; i++){
                        var fature = seltParent.markers.markers[i].feature;
                        if(fature.popup !== null){
                            if(fature.popup.id === popupId){
                                fature.popup.destroy();
                                fature.popup = null;
                            }
                        }
                    }
                }
            }
            $('#' + currentPopupId).find(".close-icon-popup-map").click(function(){
                for(var i = 0 ; i < seltParent.map.popups.length ; i++){
                    if( currentPopupId == seltParent.map.popups[i].id){
                        //remove from list popups of map object
                        seltParent.map.removePopup(selt.popup);
                        //destroy popup from feature object
                        selt.popup.destroy();
                        selt.popup = null;
                    }
                }
            });
        }
        // end for handle click of icon close popup marker 
        seltParent.currentPopup = this.popup;
        OpenLayers.Event.stop(evt);
    });
    return marker;
};

OpenStreetMap.prototype.caculateCenterPoint = function(_minLat, _minLng, _maxLat, _maxLng, _markerCount) {
    // --- set zoom level
    if(_markerCount == 1){
        zoomLevel = 14;
    }
    else{
        var latDistance = Math.abs(_maxLat - _minLat);
        var lngDistance = Math.abs(_maxLng - _minLng);
        var markerDistance = Math.sqrt(Math.pow(latDistance,2) + Math.pow(lngDistance,2));
        //--------------------------------
        if(markerDistance >= 180){
            this.zoom = 1;
        }
        else if(markerDistance >= 150){
            this.zoom = 1.5;
        }
        else if(markerDistance >= 125){
            this.zoom = 2;
        }
        else if(markerDistance >= 22.5){
            this.zoom = 2.5;
//            zoom = 1.5;
        }
        else if(markerDistance >= 11.25){
           // zoom = 3;
            this.zoom = 5;
        }
        else if(markerDistance >= 5.625){
            //zoom = 3.5;
            this.zoom = 5.5;
        }
        else if(markerDistance >= 2.813){
            //zoom = 4;
            this.zoom = 6.5;
        }
        else if(markerDistance >= 1.406){
            //zoom = 5;
            this.zoom = 7.5;
        }
        else if(markerDistance >= 0.703){
            //zoom = 6;
            this.zoom = 8.5;
        }
        else if(markerDistance >= 0.301){
            //zoom = 6.5;
            this.zoom = 10;
        }
        //------------------------------
        else if(markerDistance >= 0.150){
            this.zoom = 12;
        }
        else if(markerDistance >= 0.075){
            this.zoom = 11;
        }
        else if(markerDistance >= 0.037){
            this.zoom = 13;
        }
        else if(markerDistance >= 0.015){
            this.zoom = 13.5;
        }
        else if(markerDistance >= 0.0025){
            this.zoom = 14;
        }
        //--------------------------------
    }
     
    // --- calculate center point location
    var centerLat = 0;
    var difLatFlg = ((_minLat*_maxLat) > 0 ? 1 : -1);
    if(difLatFlg > 0){
        centerLat = (_minLat + _maxLat)/2;
    }
    else{
        centerLat = (Math.abs(_minLat) + Math.abs(_maxLat))/2 + _minLat;
    }
     
    var centerLng = 0;
    var difLngFlg = (_minLng*_maxLng > 0 ? 1 : -1);
    if(difLngFlg > 0){
        centerLng = (_minLng + _maxLng)/2;
    }
    else{
        centerLng = (Math.abs(_minLng) + Math.abs(_maxLng))/2 + _minLng;
    }
     
    var centerPoint = new OpenLayers.LonLat(centerLng, centerLat)
        .transform(
            new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
            this.map.getProjectionObject() // to Spherical Mercator Projection
        );
    return centerPoint;
};

OpenStreetMap.prototype.getLngMin = function(){
    var temp = this.arrPointMarker[0][0];
    for(var i=0 ;i<this.arrPointMarker.length;i++){
        if(parseFloat(this.arrPointMarker[i][0]) < parseFloat(temp)){
            temp = this.arrPointMarker[i][0];
        }
    }
    return temp;
};

OpenStreetMap.prototype.getLngMax = function(){
    var temp = this.arrPointMarker[0][0];
    for(var i=0 ;i<this.arrPointMarker.length;i++){
        if(parseFloat(this.arrPointMarker[i][0]) > parseFloat(temp)){
            temp = this.arrPointMarker[i][0];
        }
    }
    return temp;
};

OpenStreetMap.prototype.getLatMin = function(){
    var temp = this.arrPointMarker[0][1];
    for(var i=0 ;i<this.arrPointMarker.length;i++){
        if(parseFloat(this.arrPointMarker[i][1]) < parseFloat(temp)){
            temp = this.arrPointMarker[i][1];
        }
    }
    return temp;
};

OpenStreetMap.prototype.getLatMax = function(){
    var temp = this.arrPointMarker[0][1];
    for(var i=0 ;i<this.arrPointMarker.length;i++){
        if(parseFloat(this.arrPointMarker[i][1]) > parseFloat(temp)){
            temp = this.arrPointMarker[i][1];
        }
    }
    return temp;
};

OpenStreetMap.prototype.setDefaultVariable = function(){
    if (this.divContainer != null){
        $('#'+this.divContainer).empty();
    }
    this.arrPointMarker = [];
    this.map = null;
    this.zoom = 18;
    this.markers = null;
    this.currentPopup = null;
    this.popupClass = null;
    this.sizeIconMarker = null;
   
};

OpenStreetMap.prototype.gc = function(){
    delete this.arrPointMarker;
    delete this.map;
    delete this.zoom;
    delete this.markers;
    delete this.currentPopup;
    delete this.popupClass;
    delete this.sizeIconMarker;
    delete this.currentZoom;
    delete this.currentPointMapCenter;
    delete this.isSaveMapView;
};
// map end